import { Component, OnInit } from '@angular/core';
import { Downloader, DownloadRequest } from '@ionic-native/downloader/ngx';
import { AndroidPermissions } from '@ionic-native/android-permissions/ngx';
import { FileTransfer, FileTransferObject } from '@ionic-native/file-transfer/ngx';
import { File } from '@ionic-native/file/ngx';
import { LoadingController } from '@ionic/angular';
import { UtilsService } from '../../service/utils.service';
import { RequestService } from '../../service/request/request.service';
import { ActivatedRoute } from '@angular/router';
import Config from '../../config/index';

@Component({
  selector: 'app-document-detail',
  templateUrl: './document-detail.component.html',
  styleUrls: ['./document-detail.component.scss'],
})
export class DocumentDetailComponent implements OnInit {
  detail: any;
  filetransfer: FileTransferObject;
  loadingStatus: any;
  dowonState: number;
  constructor(
    private download: Downloader,
    private permission: AndroidPermissions,
    private transfer: FileTransfer,
    private file: File,
    private loading: LoadingController,
    private utils: UtilsService,
    private http: RequestService,
    private route: ActivatedRoute,
  ) {
    this.filetransfer = this.transfer.create();
  }

  ngOnInit() {
    this.route.queryParams.subscribe((res) => {
      this.getDeails(res.id);
    });
  }
  /**
   * 获取详情
   */
  getDeails(id) {
    this.http.get('gwgl/gwDocument/queryById', { id }).subscribe((res) => {
      console.log(res);
      if (res && res.code === 200) {
        this.detail = res.result;
      }
    });
  }
  // 文件下载
  async DownLoad(url: string, fileName = '文件') {
    // const uri = 'http://apk.start6.cn/50.pdf';
    const uri = Config.videoUrl + url;
    const fileExtend = uri.substring(uri.lastIndexOf('.') + 1);
    const resultFilePath = `${fileName}.${fileExtend}`;
    const request: DownloadRequest = {
      uri,
      title: fileName,
      description: '',
      mimeType: '',
      visibleInDownloadsUi: true,
      notificationVisibility: 0,
      destinationInExternalFilesDir: {
        dirType: 'Downloads',
        subPath: resultFilePath,
      },
    };
    /**
     * 权限申请
     */
    // this.permission.hasPermission(this.permission.PERMISSION.WRITE_EXTERNAL_STORAGE).then((res) => {
    //   console.log(res);
    // });
    this.loadingStatus = await this.loading.create({
      message: `正在下载中...`,
      backdropDismiss: false,
    });
    await this.loadingStatus.present();
    // this.filetransfer.download(uri, resultFilePath).then((res) => {});
    this.download
      .download(request)
      .then((res) => {
        this.loadingStatus.dismiss();
        this.utils.showToast(`文件下载完成,${resultFilePath}`, 'top');
      })
      .catch((err) => {
        console.log(err);
        this.loadingStatus.dismiss();
        this.utils.showToast('文件下载失败!!!', 'top');
      });
    /**
     * 其他下载方式
     */
    // const fileName = '123';
    // const fileExtend = uri.substring(uri.lastIndexOf('.') + 1);
    // const resultFilePath = this.file.dataDirectory + `${fileName}.${fileExtend}`;
    // this.filetransfer.download(uri, resultFilePath).then((res) => {
    //   console.log(res, 'hha');
    // });
    // // tslint:disable-next-line: radix
    // this.filetransfer.onProgress((val) => {
    //   // tslint:disable-next-line: radix
    //   this.dowonState = parseInt(String((val.loaded / val.total) * 100));
    //   if (this.dowonState === 100) {
    //     this.loadingStatus.dismiss();
    //     this.utils.showToast(`文件下载完成, 位置: ${resultFilePath}`, 'top');
    //     console.log(resultFilePath);
    //   }
    // });
    // this.loadingStatus = await this.loading.create({
    //   message: `正在下载中${this.dowonState}`,
    //   backdropDismiss: false,
    // });
    // await this.loadingStatus.present();
  }
}
